<template>
  <div class="user-logs-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <span>操作日志</span>
          <div class="header-actions">
            <el-button type="warning" @click="showCleanDialog">
              <el-icon><Delete /></el-icon>
              清理日志
            </el-button>
          </div>
        </div>
      </template>

      <div class="search-bar">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.username"
              placeholder="搜索用户名"
              clearable
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="searchForm.action"
              placeholder="选择操作类型"
              clearable
              style="width: 100%"
            >
              <el-option label="登录" value="login" />
              <el-option label="登出" value="logout" />
              <el-option label="创建" value="create" />
              <el-option label="更新" value="update" />
              <el-option label="删除" value="delete" />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-date-picker
              v-model="searchForm.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <el-table
        :data="logs"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="action" label="操作" width="100">
          <template #default="{ row }">
            <el-tag :type="getActionTagType(row.action)">
              {{ getActionLabel(row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="ip" label="IP地址" width="130" />
        <el-table-column prop="userAgent" label="用户代理" width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="操作时间" width="180" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showDetailDialog(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="600px"
    >
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ currentLog.username }}</el-descriptions-item>
          <el-descriptions-item label="操作">{{ getActionLabel(currentLog.action) }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
          <el-descriptions-item label="操作时间">{{ currentLog.createTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ currentLog.status }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ currentLog.description }}</el-descriptions-item>
          <el-descriptions-item label="用户代理" :span="2">{{ currentLog.userAgent }}</el-descriptions-item>
          <el-descriptions-item label="请求参数" :span="2">
            <pre>{{ currentLog.requestParams }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="响应结果" :span="2">
            <pre>{{ currentLog.responseResult }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 清理日志对话框 -->
    <el-dialog
      v-model="cleanDialogVisible"
      title="清理日志"
      width="400px"
    >
      <el-form :model="cleanForm" label-width="100px">
        <el-form-item label="清理时间">
          <el-date-picker
            v-model="cleanForm.beforeTime"
            type="datetime"
            placeholder="选择清理时间点"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="清理说明">
          <el-input
            v-model="cleanForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入清理说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cleanDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleCleanLogs" :loading="cleaning">
          确定清理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userLogApi } from '@/api/userLog'

export default {
  name: 'UserLogs',
  setup() {
    const loading = ref(false)
    const cleaning = ref(false)
    const logs = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    const detailDialogVisible = ref(false)
    const cleanDialogVisible = ref(false)
    const currentLog = ref(null)

    const searchForm = reactive({
      username: '',
      action: '',
      timeRange: []
    })

    const cleanForm = reactive({
      beforeTime: null,
      description: ''
    })

    const loadLogs = async () => {
      loading.value = true
      try {
        // 模拟API调用
        const mockLogs = [
          {
            id: 1,
            username: 'admin',
            action: 'login',
            description: '用户登录系统',
            ip: '192.168.1.100',
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            createTime: '2024-01-15 10:30:00',
            status: 'success',
            requestParams: '{"username":"admin","password":"******"}',
            responseResult: '{"code":200,"message":"登录成功"}'
          },
          {
            id: 2,
            username: 'teacher1',
            action: 'create',
            description: '创建新用户：student001',
            ip: '192.168.1.101',
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            createTime: '2024-01-15 10:25:00',
            status: 'success',
            requestParams: '{"username":"student001","email":"student001@school.com"}',
            responseResult: '{"code":200,"message":"用户创建成功"}'
          },
          {
            id: 3,
            username: 'admin',
            action: 'update',
            description: '修改角色权限配置',
            ip: '192.168.1.100',
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            createTime: '2024-01-15 10:20:00',
            status: 'success',
            requestParams: '{"roleId":1,"permissions":[1,2,3]}',
            responseResult: '{"code":200,"message":"权限更新成功"}'
          }
        ]
        logs.value = mockLogs
        total.value = mockLogs.length
      } catch (error) {
        ElMessage.error('加载日志列表失败')
      } finally {
        loading.value = false
      }
    }

    const getActionTagType = (action) => {
      const typeMap = {
        login: 'success',
        logout: 'info',
        create: 'primary',
        update: 'warning',
        delete: 'danger'
      }
      return typeMap[action] || 'info'
    }

    const getActionLabel = (action) => {
      const labelMap = {
        login: '登录',
        logout: '登出',
        create: '创建',
        update: '更新',
        delete: '删除'
      }
      return labelMap[action] || action
    }

    const showDetailDialog = (log) => {
      currentLog.value = log
      detailDialogVisible.value = true
    }

    const showCleanDialog = () => {
      cleanForm.beforeTime = null
      cleanForm.description = ''
      cleanDialogVisible.value = true
    }

    const handleSearch = () => {
      currentPage.value = 1
      loadLogs()
    }

    const handleReset = () => {
      Object.assign(searchForm, {
        username: '',
        action: '',
        timeRange: []
      })
      currentPage.value = 1
      loadLogs()
    }

    const handleCleanLogs = async () => {
      if (!cleanForm.beforeTime) {
        ElMessage.warning('请选择清理时间点')
        return
      }

      try {
        await ElMessageBox.confirm(
          `确定要清理 ${cleanForm.beforeTime} 之前的日志吗？此操作不可恢复！`,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        cleaning.value = true
        // 模拟清理操作
        await new Promise(resolve => setTimeout(resolve, 1000))
        ElMessage.success('日志清理成功')
        cleanDialogVisible.value = false
        loadLogs()
      } catch {
        // 用户取消
      } finally {
        cleaning.value = false
      }
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      loadLogs()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadLogs()
    }

    onMounted(() => {
      loadLogs()
    })

    return {
      loading,
      cleaning,
      logs,
      currentPage,
      pageSize,
      total,
      searchForm,
      cleanForm,
      detailDialogVisible,
      cleanDialogVisible,
      currentLog,
      getActionTagType,
      getActionLabel,
      showDetailDialog,
      showCleanDialog,
      handleSearch,
      handleReset,
      handleCleanLogs,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.user-logs-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.log-detail pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
}
</style> 